<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
* {
    padding: 0;
    margin: 0;
    
}

#product {
    width: 350px;
    height: 350px;
    
    margin: 100px;
    
    position: relative;
    
}

#small {
    width: 100%;
    height: 100%;
    border: 1px solid #000;
    
    position: relative;
}

#small > div {
    width: 150px;
    height: 150px;
    background-color: pink;
    opacity: 0.3;
    position: absolute;
    
    left: 30px;
    top: 0;
    
    display: none;
}

#big {
    width: 500px;
    height: 500px;
    border: 1px solid #000;
    
    overflow: hidden;
    
    position: absolute;
    
    top: 0;
    left: 350px;
    
    display: none;
}
#big > img{
    position: absolute;
}
</style>
</head>
<body>
<div id="product">
    <div id="small">
        <img src="./img/small.jpg" alt="">
        <div id="popup"></div>
    </div>
    <div id="big">
        <img src="./img/big.jpg" alt="">
    </div>
</div>
<script>
var product;
var popup;
var small;
var big;
var bigImg;

function init(){
    product = document.getElementById("product");
    popup = document.getElementById("popup");
    small = document.getElementById("small");
    
    big = document.getElementById("big")
    bigImg = document.querySelector("#big > img")
    product.onmouseover = function (){
        popup.style.display = "block";
        big.style.display = "block";

    }
    product.onmouseout = function (){
        popup.style.display = "none";
        big.style.display = "none";
    }

    var productLeft = product.offsetLeft;
    var productTop = product.offsetTop;

    product.onmousemove = function (e){
        var popupWidth = popup.offsetWidth;  // 小块的宽度的一半
        var popupHeight = popup.offsetHeight;  // 小块的宽度的一半
        var maxLeft = product.offsetWidth - popupWidth;
        var maxTop = product.offsetHeight - popupHeight;

        var x = e.pageX;   //鼠标坐标
        var y = e.pageY;   //鼠标坐标

        var left = x - productLeft - popupWidth / 2;
        var top = y - productTop - popupHeight / 2;

        //限制左边界和上边界
        left = left <= 0 ? 0 : left;
        top = top <= 0 ? 0 : top;

        //限制右边界和下边界
        left = left >= maxLeft ? maxLeft : left;
        top = top >= maxTop ? maxTop : top;

        popup.style.left = left + "px";
        popup.style.top = top + "px";
        
        bigImg.style.left = -left / maxLeft * 300 + "px";
        bigImg.style.top = -top / maxTop * 300 + "px";

    }

}

init()

</script>
</body>
</html>